﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LevelEditor.Dao;
using LevelEditor.Objects;
using DialogsEditor.DAO;
using DialogsEditor;
using LevelEditor.App;


namespace LevelEditor
{
    public partial class NewBehavior : Form
    {
        private List<Behavior> CurrentBehaviors = new List<Behavior>();
        private int CurrentSelected { get; set; }

        private Behavior newBehavior;
        public Behavior CreatedBehavior
        {
            get { return newBehavior; }
        }
      
        private DialogResult result;

        private bool wantToClose;
        private bool modifyingBehavior;
        public bool IsModifyingBehavior
        {
            get { return modifyingBehavior; }
        }

        Button viewSingleImage;
        Button viewSequence;

        private bool isSelectingBehavior;
        public bool IsSelectingBehavior
        {
            get { return isSelectingBehavior; }
            set 
            {
                this.selectButton.Visible = value;
                
                isSelectingBehavior = value; 
            }
        }

        
        public NewBehavior()
        {
            InitializeComponent();

            alterBehaviorBtn.Visible = false;

            newBehavior = new Behavior(false);

            result = System.Windows.Forms.DialogResult.Cancel;
            wantToClose = false;

            this.FormClosing += NewBehavior_FormClosing;

            txtNameBehavior.Click += txtNameBehavior_Click;
            comboProjDialogs.GotFocus += comboProjDialogs_GotFocus;

            this.selectButton.Visible = false;
        }

        public NewBehavior(Behavior toAlter)
        {
            InitializeComponent();

            this.modifyingBehavior = true;

            newBehavior = toAlter;
            alterBehaviorBtn.Visible = true;
            btnSave.Visible = false;
            result = System.Windows.Forms.DialogResult.Cancel;
            wantToClose = false;

            this.FormClosing += NewBehavior_FormClosing;
            comboProjDialogs.GotFocus += comboProjDialogs_GotFocus;

            txtNameBehavior.Click += txtNameBehavior_Click;

            behaviorDuration.Text = toAlter.DurationTime.ToString();

            txtNameBehavior.Text = newBehavior.Name;
            isWalkbehavior.Checked = newBehavior.IsWalk;

            DialogEntity d = DialogEditorDAO.GetDialogById(newBehavior.IdProjDialog);
            comboProjDialogs.Text = (d != null) ? d.title.Text: "";

            if (newBehavior.IsSpriteSheet())
            {
                AddViewSingleImageButton();
            }
            else
            {
                AddViewImageSequenceButton();
            }

            this.selectButton.Visible = false;
        }

        void txtNameBehavior_Click(object sender, EventArgs e)
        {
            wantToClose = false;
            newBehavior = new Behavior(false);
            result = System.Windows.Forms.DialogResult.Cancel;
        }

        void NewBehavior_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing && !wantToClose)
            {
                result = System.Windows.Forms.DialogResult.Cancel;
            }
        }

        private Label GetTitle()
        {
            Label title = new Label();
            title.Text = "Current Behaviors";
            title.Font = new System.Drawing.Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold);
            title.TextAlign = ContentAlignment.MiddleCenter;

            return title;
        }

        protected override void OnLoad(EventArgs e)
        {
            tablePanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 25));
            
            UpdateBehaviors();
            base.OnLoad(e);
        }

        private void RemoveBehaviors()
        {
            tablePanel.Controls.Clear();
            comboProjDialogs.Items.Clear();
        }

        void comboProjDialogs_GotFocus(object sender, EventArgs e)
        {
            comboProjDialogs.Items.Add("");
            foreach (DialogEntity dialog in DialogEditorDAO.LoadProjects())
            {
                comboProjDialogs.Items.Add(dialog.title.Text);
            }
        }

        private void UpdateBehaviors()
        {
            CurrentBehaviors = LevelEditorDAO.GetInstance().GetAllBehavior();

            tablePanel.RowCount = CurrentBehaviors.Count + 1;
            tablePanel.Controls.Add(GetTitle(), 0, 0);
            for (int i = 0; i < CurrentBehaviors.Count; i++)
            {
                Behavior b = LevelEditorDAO.GetInstance().getBehavior(CurrentBehaviors[i].Name);
                Label l = new Label();
                l.Enabled = true;
                l.Text = CurrentBehaviors[i].Name;
                l.DoubleClick += new EventHandler((sender,e) => modifyBehavior(sender, e, b));

                tablePanel.Controls.Add(l, 0, i+1);
            }
        }

        void modifyBehavior(object sender, EventArgs e, Behavior b)
        {
            if (this.IsModifyingBehavior) return;

            NewBehavior newBehaviorDialog = new NewBehavior(b);
            newBehaviorDialog.ShowDialog();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtNameBehavior.Text))
            {
                ErrorController.ShowOkError(ErrorController.LevelEditorError.APP_NO_BEHAVIOR_NAME);
                return;
            }
            else
            {
                try
                {
                    newBehavior.Name = txtNameBehavior.Text;
                    newBehavior.DurationTime = int.Parse(behaviorDuration.Text);
                    SetProjectDialog();
                    if (isWalkbehavior.Checked)
                    {
                        if (LevelEditorDAO.GetInstance().SaveWalkBehavior(newBehavior))
                        {
                            txtNameBehavior.Clear();
                            RemoveBehaviors();
                            UpdateBehaviors();
                        }
                    }
                    else
                    {
                        if (LevelEditorDAO.GetInstance().SaveBehavior((Behavior)newBehavior))
                        {
                            txtNameBehavior.Clear();
                            RemoveBehaviors();
                            UpdateBehaviors();
                        }
                    }

                    isWalkbehavior.Checked = false;
                    wantToClose = true;
                    comboProjDialogs.Text = "";
                    result = System.Windows.Forms.DialogResult.OK;
                }
                catch(Exception)
                {
                    ErrorController.ShowOkError(ErrorController.LevelEditorError.APP_CREATE_BEHAVIOR);
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (CurrentSelected <= 0 || CurrentSelected > CurrentBehaviors.Count)
            {
                ErrorController.ShowOkError(ErrorController.LevelEditorError.APP_NO_SELECTED_BEHAVIOR);
                return;
            }

            if (MessageBox.Show("Deseja apagar este behavior?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                LevelEditorDAO.GetInstance().DeleteBehavior(CurrentBehaviors[CurrentSelected - 1]);
                ClearSelected();
                RemoveBehaviors();
                UpdateBehaviors();
            }
        }

        private void SelectTrigger(object sender, EventArgs e)
        {
            Point p = Util.Util.GetPointInTablePanel(tablePanel, tablePanel.PointToClient(Cursor.Position));
            if (p.IsEmpty || p.Y == 0)
            {
                ClearSelected();
                return;
            }
            CurrentSelected = p.Y; //Row selected

            for (int row = 0; row < tablePanel.RowCount; row++)
            {
                Control control = tablePanel.GetControlFromPosition(0, row);
                if (row == CurrentSelected)
                    control.BackColor = Color.Blue;
                else
                    control.BackColor = Color.Transparent;
            }

        }

        private void ClearSelected()
        {
            if (CurrentSelected <= 0) return;
            tablePanel.GetControlFromPosition(0, CurrentSelected).BackColor = Color.Transparent;
            CurrentSelected = -1;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ClearSelected();
        }

        private void DisableLoadButtons()
        {
            loadImageSequence.Visible = false;
            loadImageSequence.Enabled = false;
            loadSpriteSheet.Visible = false;
            loadSpriteSheet.Enabled = false;
        }

        private void AddViewImageSequenceButton()
        {
            if (viewSingleImage != null)
            {
                loadImageSequence.Parent.Controls.Remove(viewSingleImage);
                viewSingleImage = null;
            }

            viewSequence = new Button();
            viewSequence.Location = new Point(loadSpriteSheet.Location.X + loadSpriteSheet.Width, loadSpriteSheet.Location.Y);
            viewSequence.Width = loadImageSequence.Width;
            viewSequence.Text = "View Sequence";
            viewSequence.Click += viewSequence_Click;

            loadImageSequence.Parent.Controls.Add(viewSequence);
        }

        private void AddViewSingleImageButton()
        {
            if (viewSequence != null)
            {
                loadImageSequence.Parent.Controls.Remove(viewSequence);
                viewSequence = null;
            }

            viewSingleImage = new Button();
            viewSingleImage.Location = new Point(loadSpriteSheet.Location.X + loadSpriteSheet.Width, loadSpriteSheet.Location.Y);
            viewSingleImage.Width = loadImageSequence.Width;
            viewSingleImage.Text = "View Sheet";
            viewSingleImage.Click += viewSingleImage_Click;

            loadImageSequence.Parent.Controls.Add(viewSingleImage);
        }

        void viewSingleImage_Click(object sender, EventArgs e)
        {
            LoadSpriteSheet lSpriteSheet = new LoadSpriteSheet(newBehavior.Images[0]);
            lSpriteSheet.ShowDialog();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            LoadImageSequence lImageSequence = new LoadImageSequence();

            if (lImageSequence.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                DisableLoadButtons();

                AddViewImageSequenceButton();

                newBehavior.Images = lImageSequence.LoadedImages;
            }
        }

        void viewSequence_Click(object sender, EventArgs e)
        {
            LoadImageSequence lImageSequence = new LoadImageSequence(newBehavior.Images, false);

            lImageSequence.ShowDialog();

        }

        private void loadSpriteSheet_Click(object sender, EventArgs e)
        {
            LoadSpriteSheet lSpriteSheet = new LoadSpriteSheet();
            if (lSpriteSheet.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                newBehavior.Images.Add(lSpriteSheet.LoadedSpriteSheet);

                DisableLoadButtons();

                AddViewSingleImageButton();
            }
        }

        public new DialogResult ShowDialog()
        {
            base.ShowDialog();

            return result;
        }

        private void isWalkbehavior_CheckedChanged(object sender, EventArgs e)
        {
            newBehavior.IsWalk = isWalkbehavior.Checked;
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtNameBehavior.Text))
            {
                ErrorController.ShowOkError(ErrorController.LevelEditorError.APP_NO_BEHAVIOR_NAME);
                return;
            }
            else
            {
                try
                {
                    newBehavior.Name = txtNameBehavior.Text;
                    SetProjectDialog();
                    if (LevelEditorDAO.GetInstance().UpdateBehavior((Behavior)newBehavior))
                    {
                        txtNameBehavior.Clear();
                        RemoveBehaviors();
                        UpdateBehaviors();
                    }

                    comboProjDialogs.Text = "";
                    isWalkbehavior.Checked = false;
                    wantToClose = true;
                    result = System.Windows.Forms.DialogResult.OK;
                    txtNameBehavior.Text = "";
                }
                catch (Exception)
                {
                    ErrorController.ShowOkError(ErrorController.LevelEditorError.APP_UPDATE_BEHAVIOR);
                }
            }
        }



        private void SetProjectDialog()
        {
            if (string.IsNullOrEmpty(comboProjDialogs.Text) || string.IsNullOrWhiteSpace(comboProjDialogs.Text))
            {
                newBehavior.IdProjDialog = 0;
            }

            foreach (DialogEntity dialog in DialogEditorDAO.LoadProjects())
            {
                if (comboProjDialogs.Text == dialog.title.Text)
                {
                    newBehavior.IdProjDialog = dialog.GetID();
                    break;
                }
            }
        }

        private void selectButton_Click(object sender, EventArgs e)
        {
            string behaviorName = tablePanel.GetControlFromPosition(0, CurrentSelected).Text;

            newBehavior = LevelEditorDAO.GetInstance().getBehavior(behaviorName);
            
            this.result = System.Windows.Forms.DialogResult.OK;
            this.wantToClose = true;
            this.Close();
        }

        private void tablePanel_Paint(object sender, PaintEventArgs e)
        {

        }

    }
}
